/**
 * Select the text of a HTML element
 * @see https://github.com/zenorocha/select
 * @param element
 * @returns {string}
 */
export default function select(element) {
  let selectedText;

  if (element.nodeName === "SELECT") {
    element.focus();

    selectedText = element.value;
  } else if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") {
    const isReadOnly = element.hasAttribute("readonly");

    if (!isReadOnly) {
      element.setAttribute("readonly", "");
    }

    element.select();
    element.setSelectionRange(0, element.value.length);

    if (!isReadOnly) {
      element.removeAttribute("readonly");
    }

    selectedText = element.value;
  } else {
    if (element.hasAttribute("contenteditable")) {
      element.focus();
    }

    const selection = window.getSelection();
    const range = document.createRange();

    range.selectNodeContents(element);
    selection.removeAllRanges();
    selection.addRange(range);

    selectedText = selection.toString();
  }

  return selectedText;
}
